use chrono::{NaiveDateTime, Utc};
use serde::{Serialize, Deserialize};

extern crate serde;
extern crate serde_json;
use serde_json::{json, Value};

use rocket::{catch, catcher, delete, get, put, post, routes, catchers, build};
use std::fs;
use sqlx;
use std::env;
use sqlx::postgres::PgRow;
use sqlx::{postgres::PgPoolOptions, Executor, postgres::PgPool, Row};
use sqlx::FromRow;
use crate::tools::settings::{Setting};
use crate::service::db::{execute, pgsql_conn};
use chrono::NaiveDate;
use rocket::tokio::time::{sleep, Duration};
use rocket::serde::{json::Json};
#[get("/browse/<id>")]
pub async fn browse(id: u64) -> String {
    // sleep(Duration::from_secs(seconds)).await;
    format!("browse {}", id)
}


//派生宏
#[derive(Debug, Deserialize, Serialize, sqlx::FromRow)]
pub struct ModelResUsers {
    id: i32,
    company_id: i32,
    active: bool,
    create_date: NaiveDateTime,
    write_date: NaiveDateTime,
    login: String,
    password: String,
    signature: String,
    share: bool,
    partner_id: ModelResPartner,
}

impl Default for ModelResUsers {
    fn default() -> Self {
        Self {
            id: 0,
            company_id: 1,
            active: true,
            create_date: Utc::now().naive_utc(),
            write_date: Utc::now().naive_utc(),
            login: String::new(),
            password: String::new(),
            signature: String::new(),
            share: false,
            partner_id: ModelResPartner::default(),
            // email: String::from("example@example.com"),
        }
    }
}

#[derive(Debug, Deserialize, Serialize)]
struct ModelResPartner {
    id: u64,
    name: String,
}

impl Default for ModelResPartner {
    fn default() -> ModelResPartner {
        ModelResPartner {
            id: 0,
            name: String::new(),
        }
    }
}


//登陆
pub async fn login(login: String, password: String) -> sqlx::Result<()> {
    let mut data = ModelResUsers::default();
    //数据连接池
    let pool = crate::service::db::pgsql_conn().await?;

    let sql = "SELECT id,company_id,active,create_date,write_date,login,password,signature,share FROM res_users where id=2";
    let mut rows = crate::service::db::execute(pool, sql).await;


    //结构体绑定数据
    for res in rows.iter()
    {
        let id: i32 = res.get("id");
        data.id = id;

        let company_id: i32 = res.get("company_id");
        data.company_id = company_id;

        let active: bool = res.get("active");
        data.active = active;

        let create_date_str: NaiveDateTime = res.get("create_date");

        data.create_date = create_date_str;

        let write_date: NaiveDateTime = res.get("write_date");
        data.write_date = write_date;

        let login: String = res.get("login");
        data.login = login;

        let password: String = res.get("password");
        data.password = password;

        let signature: String = res.get("signature");
        data.signature = signature;

        let share: bool = res.get("share");
        data.share = share;
    }


    println!("{:?}", data);


    // for row in rows
    // {
    //     let column:u32 = res.get("id");
    //
    //         // let id: i32 = row.id; // 假设id是i32类型
    //         // let name: String = row.login; // 假设name是String类型
    //         // println!("ID: {}, Name: {}", id, name);
    //     // let column: String = res.get("login");
    //     //
    //     println!("{}",column);
    //
    //     // data.id = id;
    //     // data.login =res.get("login").to_string();
    //
    // }


    // data.id = 15;
    // data.partner_id.id =20;
    // data.partner_id.name ="张三".to_string();
    // // data.login = String::from("Alice");
    //
    //
    // let json_str = serde_json::to_string(&data).unwrap();
    // println!("{}", json_str);
    //
    // println!("AAAAAAAAAAA");


    // json!({
    //     "message": "input",
    //     "success": true
    // })


    // let json_str = json::stringify(data);
// 还是使用这个因团队而异
    // let json_str = data.dump();


    Ok(())
}

//注册
pub async fn signup() -> Result<(), Box<dyn std::error::Error>> {

    // let url = "postgres://odoo:123456@localhost:5432/odoo17";
    // let mut pool = sqlx::postgres::PgConnection::connect(url).await?;
    //
    // let query ="INSERT INTO res_users(company_id,partner_id,login,notification_type) VALUES (1,3,'aa1','email')";
    // sqlx::query(query).execute(pool)?;
    //
    //
    //
    // println!("用户表");



    Ok(())
}

//修改密码
pub fn reset_password() {
    println!("用户表")
}

#[derive(Debug, Deserialize)]
#[serde(crate = "rocket::serde")]
struct Param {
    keyword: String,
    // active: bool,
    // id: i32
}


//分页
#[post("/page", format = "application/json", data = "<param>")]
pub fn page(param:Json<Param>)-> Json<ModelResUsers> {
    println!("qqqqqq{:?}", param);

    // 返回处理后的任务
    let mut data = ModelResUsers::default();
    Json(data)

}

fn str_to_json(s: &str) -> Result<Value, serde_json::Error> {
    serde_json::from_str(s)
}

//分页
#[post("/create", format = "application/json", data = "<param>")]
pub fn create(param:&str)-> Json<ModelResUsers> {
    // 提交的参数进行解析
    let v: Value = serde_json::from_str(param).expect("REASON");
    println!("取一个值 param: {:?}", v["keyword"]);


    // 返回处理后的任务
    let mut data = ModelResUsers::default();
    Json(data)

}



//删除
pub fn delete() {
    println!("用户表")
}

//修改
pub fn write() {
    println!("用户表")
}

//导入
pub fn import() {
    println!("用户表")
}

//导出
pub fn export_xlsx() {
    println!("用户表")
}